<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" size="large" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable style="width: 200px">
          <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="当前阶段" prop="phaseCode">
        <el-input v-model="queryParams.phaseName" placeholder="请输入当前阶段" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="预计验收日期" style="width: 308px">
        <el-date-picker v-model="daterangeAcceptTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="立项金额">
        <div style="display: flex; align-items: center;">
          <el-input v-model="queryParams.minProjectAmount" placeholder="最小金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-right: 10px;" />
          -
          <el-input v-model="queryParams.maxProjectAmount" placeholder="最大金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-left: 10px;" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>

        <!-- <el-button type="primary" icon="Search" @click="handleSync">同步数据</el-button> -->
      </el-form-item>
    </el-form>

    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>


    <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
      <el-checkbox-group v-model="selectedProps">
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
          {{ col.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
    </div>
    <el-table v-loading="loading" :data="projectList" border>
      <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
        :align="'center'"
        :show-overflow-tooltip="['contractAmount', 'settlementAmount', 'housekeeperName'].includes(col.prop)"
        :width="getWidth(col.prop)">
        <!-- 特殊列的插槽处理 -->
        <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
          <span>{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 固定操作列 -->
      <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? 80 : 220" align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" :icon="userStore.isMobile ? '' : 'View'"
            @click="handleView(scope.row)">查看</el-button>
          <el-button link type="primary" :icon="userStore.isMobile ? '' : 'Edit'"
            @click="handleUpdate(scope.row)">添加</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />


    <!-- 添加或修改绩效基本信息对话框 -->



    <el-dialog @close="cancel" fullscreen v-model="open" width="800px" append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">

          <!-- <projectView :datas="form"  :key="form.projectNo" :column="3" :sizes="'large'"></projectView> -->

          <el-form ref="projectRef" :disabled="formDisabled" :model="form" label-position="left" :rules="rules"
            :label-width="userStore.isMobile ? '100px' : '120px'" size="large">
            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="form.projectName" placeholder="请输入项目名称" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="归属公司" prop="companyType">
                  <el-select @change="setCompanyTypeName" v-model="form.companyType" placeholder="请选择归属公司"
                    style="width: 100%">
                    <el-option v-for="dict in company_type" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="项目类型" prop="projectType">
                  <el-select @change="setProjectTypeName" v-model="form.projectType" placeholder="请选择项目类型"
                    style="width: 100%">
                    <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 发起人相关 -->
            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="发起人" prop="createDeptName">
                  <el-input disabled v-model="form.createUserName" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="发起人所在部门" prop="createDeptName">
                  <el-input disabled v-model="form.createDeptName" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="发起时间" prop="startDate">
                  <el-date-picker disabled clearable v-model="form.createTime" type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发起时间" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 金额字段 -->
            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="立项金额(元)" prop="projectAmount">
                  <el-input type="number" @wheel.native.prevent v-model="form.projectAmount" placeholder="请输入立项金额"
                    style="width: 100%">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="合同金额(元)" prop="contractAmount">
                  <el-input type="number" @wheel.native.prevent v-model="form.contractAmount" placeholder="请输入合同金额"
                    style="width: 100%">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="结算金额(元)" prop="settlementAmount">
                  <el-input type="number" disabled @wheel.native.prevent v-model="form.settlementAmount"
                    placeholder="请输入结算金额" style="width: 100%">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 其他行依此类推 -->

            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="管家婆项目" prop="housekeeperProject">
                  <el-select v-model="form.housekeeperProject" filterable clearable remote reserve-keyword
                    placeholder="请输入关键字" :remote-method="selectCompany" :loading="loadingQuery" style="width: 100%"
                    @change="setHousekeeperName">
                    <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="合同签订日期" prop="planDate">
                  <el-date-picker clearable v-model="form.planDate" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择合同签订日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="预计验收日期" prop="acceptTime">
                  <el-date-picker clearable v-model="form.acceptTime" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择预计验收日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="立项日期" prop="approvalDate">
                  <el-date-picker clearable v-model="form.approvalDate" type="date" value-format="YYYY-MM-DD"
                    placeholder="立项日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="客户名称" prop="customerName">
                  <el-input v-model="form.customerName" placeholder="请输入客户名称" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="客户地址" prop="customerAddress">
                  <el-input v-model="form.customerAddress" placeholder="请输入客户地址" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="项目配合单位" prop="projectUnit">
                  <el-input v-model="form.projectUnit" placeholder="请输入项目配合单位" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="阶段确认人" prop="joinPeople">
                  <el-input v-model="form.joinPeople" :disabled="true" style="width: 100%" />
                </el-form-item>
              </el-col>


              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="项目保险单" prop="policy">
                  <el-select @change="policyChange" v-model="form.policy" placeholder="请选择是否有项目保险单" style="width: 100%">
                    <el-option v-for="dict in policy_type" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <!-- <el-tooltip effect="dark" content="保险单必须由项目经理上传">
                <el-form-item label="上传附件" prop="policyFile">
                  <file-upload v-if="uploadPolicy && form.policy == '2'" :limit="1" v-model="form.policyFile" />
                  <el-button v-else disabled type="primary"> 上传附件 </el-button>
                </el-form-item>
              </el-tooltip> -->

              <el-tooltip effect="dark" content="保险单必须由项目经理上传">
                <el-form-item label="保险单附件" prop="policyFile">
                  <file-upload v-if="uploadPolicy && form.policy == '2'" :isShowTip="false"
                    :showText="form.policyFile == null || form.policyFile == undefined || form.policyFile == ''"
                    :limit="1" v-model="form.policyFile" />
                  <el-button v-else disabled type="primary"
                    v-if="form.policyFile == null || form.policyFile == undefined || form.policyFile == ''">
                    上传附件 </el-button>
                </el-form-item>
              </el-tooltip>


            </el-row>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" style="width: 100%" />
            </el-form-item>

            <el-divider style="font-size: 16px; font-weight: bold;">环节留言</el-divider>
            <el-form-item label="留言" prop="phaseRemark">
              <el-input v-model="form.phaseRemark" type="textarea" :rows="3" placeholder="请输入留言" style="width: 100%" />
            </el-form-item>
          </el-form>
          <amountView :projectNo="amountViewProjectNo" :key="amountViewProjectNo"></amountView>

          <el-divider style="font-size: 16px; font-weight: bold;">参与人员信息</el-divider>
          <el-button :disabled="!addPersonPer" type="primary" plain :icon="Plus" @click="addPerson()"
            style="margin-bottom: 10px;">添加参与人员</el-button>
          <el-table v-loading="loading" :data="personList" border @selection-change="handleSelectionChange">
            <el-table-column label="标签页" align="center" width="180" prop="phaseName" />
            <el-table-column label="参与人" align="center" width="200" prop="participanName" />
            <el-table-column label="岗位" align="center" prop="postName" />
            <el-table-column label="开始日期" align="center" width="120" prop="startDate" />
            <el-table-column label="结束日期" align="center" prop="endDate" />
            <el-table-column label="备注" align="center" width="120" prop="remark" />
            <el-table-column label="操作员" align="center" prop="operator" />
            <el-table-column label="操作时间" align="center" prop="startDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? 120 : 220" align="center"
              class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button :disabled="!addPersonPer" link type="primary" :icon="userStore.isMobile ? '' : 'Edit'"
                  @click="handleUpdateParticipan(scope.row)">修改</el-button>
                <el-button :disabled="!addPersonPer" link type="primary" :width="userStore.isMobile ? 120 : 220"
                  @click="handleDeleteParticipan(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-divider style="font-size: 16px; font-weight: bold;">附件信息</el-divider>
          <el-button :disabled="!addFilePer" type="primary" plain :icon="Plus" @click="addFiles()"
            style="margin-bottom: 10px;">添加附件信息</el-button>
          <el-table v-loading="loading" :data="attachmentList" border @selection-change="handleSelectionChange">
            <el-table-column label="标签页" align="center" prop="phaseName" />
            <el-table-column label="附件类别" align="center" prop="attachmentType">
              <template #default="scope">
                <dict-tag :options="file_type" :value="scope.row.attachmentType" />
              </template>
            </el-table-column>
            <el-table-column label="附件标题" align="center" prop="attachmentTitle" />
            <el-table-column label="附件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
              <template #default="scope">
                <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
              </template>
            </el-table-column>
            <el-table-column label="操作员" align="center" prop="operator" />
            <el-table-column label="操作时间" align="center" prop="startDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" :width="userStore.isMobile ? 120 : 220"
              class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button :disabled="!addFilePer" link type="primary" :icon="userStore.isMobile ? '' : 'Edit'"
                  @click="handleUpdateFile(scope.row)">修改</el-button>
                <el-button :disabled="!addFilePer" link type="primary" :icon="userStore.isMobile ? '' : 'Delete'"
                  @click="handleDeleteFile(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 是否有 超级管理员 项目经理 销售 销售负责人 商务 财务权限之一  -->
          <div>
            <el-divider style="font-size: 16px; font-weight: bold;">实施日志信息</el-divider>
            <el-button :disabled="!addImplementPer" type="primary" plain :icon="Plus" @click="addImplements()"
              style="margin-bottom: 10px;">添加实施工作日志</el-button>
            <el-table v-loading="loading" border :data="implementList" @selection-change="handleSelectionChange">
              <!-- <el-table-column label="关联的阶段id" align="center" prop="phaseId" /> -->
              <el-table-column label="实施日期" align="center" prop="implementDate" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.implementDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="附件照片" align="center" prop="images" width="100">
                <template #default="scope">
                  <image-preview v-if="scope.row.images" :src="scope.row.images" :width="50" :height="50" />
                </template>
              </el-table-column>
              <!-- <el-table-column label="附件" align="center" prop="files" /> -->
              <el-table-column label="标题" align="center" prop="title" />
              <el-table-column label="内容" align="center" prop="remark" />
              <!-- <el-table-column label="文件名称" align="center" prop="fileName" /> -->
              <!-- <el-table-column label="文件类型" align="center" prop="fileType">
                <template #default="scope">
                  <dict-tag :options="log_type" :value="scope.row.fileType" />
                </template>
              </el-table-column> -->
              <!-- <el-table-column label="附件" align="center" show-overflow-tooltip width="200" prop="fileName">
              <template #default="scope">
                <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
              </template>
            </el-table-column> -->

              <!-- <el-table-column label="附件" align="center" width="250">
                <template #default="scope">
                  <div v-if="hasFiles(scope.row)">
                    <el-link v-for="(file, index) in scope.row.files.split(',')" :key="index" type="primary"
                      @click="downloadFileImp(file)" style="display: block; margin-bottom: 4px;">
                      {{ getFileNameImp(file) }}
                    </el-link>
                  </div>
                  <div v-else>--</div>
                </template>
              </el-table-column> -->

              <el-table-column label="附件" align="center" width="250">
                <template #default="scope">
                  <div v-if="hasFiles(scope.row)">
                    <div v-for="(file, index) in scope.row.files.split(',')" :key="index" style="margin-bottom: 4px;">
                      <!-- 判断是否是图片 -->
                      <template v-if="isImage(file)">
                        <image-preview :src="file" :width="50" :height="50" />
                      </template>
                      <template v-else>
                        <el-link type="primary" @click="downloadFileImp(file)">
                          {{ getFileNameImp(file) }}
                        </el-link>
                      </template>
                    </div>
                  </div>
                  <div v-else>--</div>
                </template>
              </el-table-column>




              <el-table-column label="操作人" align="center" prop="operator" />
              <el-table-column label="操作时间" align="center" prop="startDate" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center" fixed="right" :width="userStore.isMobile ? 120 : 220"
                class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link :disabled="!addImplementPer" type="primary" :icon="userStore.isMobile ? '' : 'Edit'"
                    @click="handleUpdateImplement(scope.row)">修改</el-button>
                  <el-button link :disabled="!addImplementPer" type="primary" :icon="userStore.isMobile ? '' : 'Delete'"
                    @click="handleDeleteImplement(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="正式清单" name="second">
          <mainList v-if="activeName == 'second'" :datas="form"></mainList>
        </el-tab-pane>
        <el-tab-pane label="管家婆出库单" name="third">
          <saleList v-if="activeName == 'third'" :datas="form"></saleList>
        </el-tab-pane>
        <el-tab-pane label="费用汇总" name="four">
          <feeList v-if="activeName == 'four'" :datas="form"></feeList>
        </el-tab-pane>
        <el-tab-pane label="清单对比" name="five">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>
        <el-tab-pane label="其他信息" name="six">
          <joinPerson :personList="personList" :attachmentList="attachmentList" :payList="payList"
            :implementList="implementList" v-if="activeName == 'six'" :datas="form"></joinPerson>
        </el-tab-pane>

        <el-tab-pane label="配套施工清单" name="seven">
          <matching v-if="activeName == 'seven'" :datas="form"></matching>
        </el-tab-pane>


      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="manger" type="primary" @click="updateForm">修改项目信息</el-button>
          <el-popconfirm v-if="status == 1 && haveNext" confirm-button-text="确认" cancel-button-text="取消"
            title="确认提交到下一步?" @confirm="nextPhase">
            <template #reference>
              <el-button type="primary">下一步</el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改项目参加人员子对话框 -->
    <el-dialog title="参与人员" v-model="openOper" :width="userStore.isMobile ? '95%' : '800px'" append-to-body>
      <el-form ref="participanRef" :model="personForm" size="large" :rules="personRules" label-width="120px">
        <el-form-item label="参与人" prop="participantId">
          <el-select @change="setPersonName" filterable v-model="personForm.participantId" placeholder="请选择参与人"
            clearable style="width: 200px;">
            <el-option v-for="dict in userList" clearable :key="dict.userId" :label="dict.nickName"
              :value="dict.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与人岗位" prop="postId">
          <el-select @change="setPostName" filterable v-model="personForm.postId" placeholder="请选择岗位" clearable
            style="width: 200px;">
            <el-option v-for="dict in posts" clearable :key="dict.postId" :label="dict.postName"
              :value="dict.postId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable v-model="personForm.startDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable v-model="personForm.endDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="personForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPersonForm">确 定</el-button>
          <el-button @click="cancelPerson">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 添加或修改附件对话框 -->
    <el-dialog title="附件信息" v-model="openFile" :width="userStore.isMobile ? '95%' : '800px'" append-to-body>
      <el-form ref="attachmentRef" :model="fileForm" size="large" :rules="fileRules" label-width="80px">
        <el-form-item label="附件类别" prop="attachmentType">
          <el-select @change="setUploadType" v-model="fileForm.attachmentType" placeholder="请选择附件类别">
            <el-option v-for="dict in file_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <template v-if="fileForm.attachmentType == 6"><el-tag type="primary"
            style="margin-left: 85px;">上传竣工报告时必须填写竣工日期</el-tag></template>

        <el-form-item v-if="fileForm.attachmentType == 6" label="竣工日期" prop="approvalDate">
          <el-date-picker clearable v-model="fileForm.completeDate" type="date" value-format="YYYY-MM-DD"
            placeholder="竣工日期" style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="附件标题" prop="attachmentTitle">
          <el-input v-model="fileForm.attachmentTitle" placeholder="请输入附件标题" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="fileForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传附件" prop="filePath">
          <file-upload :limit="1" :fileType="fileAccept" v-model="fileForm.filePath" />
        </el-form-item>
        <template v-if="fileForm.attachmentType == 5 || fileForm.attachmentType == 22"><el-tag type="primary"
            style="margin-left: 10px;">提示：多次导入正式或结算清单或会以最后一份为准</el-tag></template>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelFile">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改付款对话框 -->
    <el-dialog title="实施日志" v-model="openImplement" :width="userStore.isMobile ? '95%' : '800px'" append-to-body>
      <el-form ref="implementRef" size="large" :model="implementForm" :rules="ImplementRules" label-width="100px">

        <el-form-item label="实施日期" prop="implementDate">
          <el-date-picker clearable v-model="implementForm.implementDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择实施日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input clearable v-model="implementForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="remark">
          <el-input clearable v-model="implementForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="附件照片" prop="images">
          <image-upload v-model="implementForm.images" />
        </el-form-item>

        <el-form-item label="上传附件" prop="filePath">
          <file-upload v-model="implementForm.files" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitimplementForm">确 定</el-button>
          <el-button @click="canceImplement">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog v-model="openView" fullscreen width="1000px" append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">
          <projectView :datas="form" :key="'projectView' + form.projectNo" :sizes="'large'" :isView="isView" :column="3"
            :personList="personList" :attachmentList="attachmentList" :payList="payList" :implementList="implementList">
          </projectView>

        </el-tab-pane>
        <el-tab-pane label="正式清单" name="second">
          <mainList v-if="activeName == 'second'" :datas="form"></mainList>
        </el-tab-pane>
        <el-tab-pane label="管家婆出库单" name="third">
          <saleList v-if="activeName == 'third'" :datas="form"></saleList>
        </el-tab-pane>
        <el-tab-pane label="费用汇总" name="four">
          <feeList v-if="activeName == 'four'" :datas="form"></feeList>
        </el-tab-pane>
        <el-tab-pane label="清单对比" name="five">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>

        <el-tab-pane label="配套施工清单" name="seven">
          <matching v-if="activeName == 'seven'" :datas="form"></matching>
        </el-tab-pane>


      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Project">
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject, listCompany,
  syncData,
  getCompanyList,
  getFinanceList,
  listParticipan, getParticipan, delParticipan, addParticipan, updateParticipan, getPermission,
  getStatus, saveUserTableConfig, getUserTableConfig, getMessage,
  listImplement, getImplement, delImplement, addImplement, updateImplement, listPay
} from "@/api/project/project";
import { listAttachment, getAttachment, delAttachment, addAttachment, updateAttachment } from "@/api/project/project";
import { listPhase, getPhase, delPhase, addPhase, updatePhase } from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import { getInfo } from "@/api/login";
import { listAllUser, getUser, getPosts } from "@/api/system/user";

import { getCheck, getNextPermission, listDictionary, getDictionary, delDictionary, addDictionary, updateDictionary, listAllDictionary } from "@/api/project/dictionary";
const haveNext = ref(false)

import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();

const addPersonPer = ref(false)
const addFilePer = ref(false)
const addPayPer = ref(false)
const addImplementPer = ref(false)
const addWarrantyPer = ref(false)
const addAccounting = ref(false)
const manger = ref(false);//当前人员是否项目经理或销售负责人
const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { policy_type } = proxy.useDict("policy_type");
const { phase_type } = proxy.useDict("phase_type");
const { file_type } = proxy.useDict('file_type');
const { log_type } = proxy.useDict('log_type');
const { company_type } = proxy.useDict("company_type");
const attachmentList = ref([]);
const implementList = ref([]);
const payList = ref([]);
const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const companyList = ref([]);
const financeList = ref([]);
const open = ref(false);
const isView = ref(false);
const openView = ref(false);
const openOper = ref(false);
const openPhase = ref(false);
const openFile = ref(false);
const openImplement = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const projectNo = ref("")
const contractAmount = ref(0)
const finance = ref(false);//当期人员是否是财务
const isAdmin = ref(false);//是否是超级管理员
const haveImplement = ref(false);//是否有添加实施日志信息的权限
const haveAddPerson = ref(false);//是否有添加参与人员的权限
const status = ref("0");
const currenrPhaseId = ref()
const loadingQuery = ref(false)
function fileChange(file) {
  console.log("上传文件：", file);

}
const fileAccept = ref(["doc", "docx", "cad", "dwg", "xls", "ppt", "txt", "pdf", "xlsx", 'png', 'jpg', 'jpeg'],);
function setUploadType(selection) {
  console.log("选择的文件类型", selection);
  const temp = ["doc", "docx", "cad", "dwg", "dwg", "xls", "ppt", "txt", "pdf", "xlsx", 'png', 'jpg', 'jpeg'];
  if (selection == 5 || selection == 22) {//正式清单 只允许上传excel
    fileAccept.value = ["xls", "xlsx"]
  } else {
    fileAccept.value = temp
  }
}

// 判断是否有文件
function hasFiles(row) {
  return row.files && typeof row.files === 'string' && row.files.trim() !== '';
}

// 提取文件名
function getFileNameImp(filePath) {
  if (!filePath) return '';

  // 1. 提取文件名部分（带扩展名）
  const fileNameWithExt = filePath.split('/').pop();

  // 2. 分离文件名和扩展名
  const lastDotIndex = fileNameWithExt.lastIndexOf('.');
  if (lastDotIndex === -1) return fileNameWithExt;

  const ext = fileNameWithExt.slice(lastDotIndex); // .docx / .png 等
  let baseName = fileNameWithExt.slice(0, lastDotIndex); // 去掉扩展名的部分

  // 3. 取第一个 '_' 前面的内容
  const firstUnderscoreIndex = baseName.indexOf('_');
  if (firstUnderscoreIndex > 0) {
    baseName = baseName.substring(0, firstUnderscoreIndex);
  }
  // 如果没有 '_'，则保持原样

  // 4. 返回美化后的文件名
  return baseName + ext;
}


import mainList from "../mainList.vue";
import saleList from "../saleList.vue";
import feeList from "../fee.vue"
import compareMainAndSale from "../compareMainAndSale.vue"
import joinPerson from "../joinPerson.vue"
import matching from "../matching.vue"
const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}

async function updateForm() {
  await updateProject(form.value).then((response) => {
    proxy.$modal.msgSuccess("修改成功");
  });
  let params = {
    projectNo: form.value.projectNo
  }

  listPay(params).then((response) => {
    payList.value = response.data;
  });

  listParticipan(params).then((response) => {
    console.log("response", response);
    personList.value = response.data
  });




}


// 提取文件名
const fileName = computed(() => {
  if (!props.row.files) return '';
  const paths = props.row.files?.split(',');
  return paths.map(path => path.split('/').pop()).join(', ');
});

// 下载方法
const downloadFileImp = (file) => {
  console.log("filePath", file)
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + file)
  a.click()
};

import { ElLoading } from 'element-plus'
const phasetList = ref([]);
const formDisabled = ref(true);
let currentPhase = reactive({
  phaseCode: '',
});
import projectView from "../projectView.vue";
import { ref } from "vue";
import { pa } from "element-plus/es/locale/index.mjs";
import { ElNotification } from 'element-plus'
const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  currentConfig: {//当前环节关联的配置表

  },
  personForm: {
  },
  fileForm: {

  },
  implementForm: {

  },

  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: 1,
    phaseId: 3,
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
  },
  personRules: {
    postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
    participantId: [{ required: true, message: "参与人不能为空", trigger: "blur" }],
  },

  fileRules: {
    attachmentType: [{ required: true, message: "请选择附件类型", trigger: "blur" }],
    filePath: [{ required: true, message: "请上传附件", trigger: "blur" }],
  },

  ImplementRules: {
    implementDate: [{ required: true, message: "请选择实施日期", trigger: "blur" }],
  }

});


function handleBlur(type) {
  if (type == 1) {
    const percentage = parseFloat(implementForm.value.percentage);
    console.log(`付款百分比为: ${percentage}%`);
    // 计算金额并保留两位小数
    implementForm.value.amount = parseFloat((percentage / 100 * implementForm.value.totalAmount).toFixed(2));
    console.log(`计算后的金额为: ${implementForm.amount}`);
  } else {
    const percentage = parseFloat(implementForm.value.percentage);

    console.log(`付款百分比为: ${percentage}%`);
    // 计算金额并保留两位小数
    implementForm.value.receivedPercentage = parseFloat((implementForm.value.receivedAmount / implementForm.value.totalAmount * 100).toFixed(2));
    console.log(`百分比: ${implementForm.value.receivedPercentaget}`);
  }

}
let notificationInstance = null
function openMessage() {

  let param = {
    stage: 3,
    projectNo: projectNo.value
  }

  getMessage(param).then(res => {
    if (res.data.length > 0) {
      open1(res.data)
    }
  });


}

const open1 = (datas) => {
  if (!datas || datas.length === 0) return;

  // 构建每个项目的截止日期信息
  const deadlineLines = datas
    .map(item => {
      return `
      <div style="margin-top: 8px;">
        <span style="color: #626aef; font-weight: bold;">${item}</span><br>
      </div>
    `;
    });

  // 拼接最终消息内容
  const notificationMessage = `
  <div style="margin-bottom: 10px; font-weight: bold; color: black;">
    您可提交的材料有:
  </div>
  ${deadlineLines.join('')}
`;

  // 创建通知
  notificationInstance = ElNotification({
    title: '通知',
    message: h('div', {
      style: {
        whiteSpace: 'normal',
        wordBreak: 'break-word',
        lineHeight: '1.5'
      },
      innerHTML: notificationMessage
    }),
    duration: 0,
    customClass: 'my-custom-notification'
  });
};

// import {getPermission} from "@/api/project/project";
async function downloadFile(row) {
  //只有项目经理 销售负责人 吴总 能够下载正式清单 竣工结算清单 正式合同
  if (row.attachmentType == '4' || row.attachmentType == '5' || row.attachmentType == '22') {
    let params = {
      projectNo: row.projectNo,
      postIds: [2, 5, 6, 7]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    const res = await getPermission(params).then((response) => {
      console.log("下载附件", response.data);
      return response.data
    });
    if (!res) {
      proxy.$modal.msgError("暂无权限下载此附件");
      return
    }
  }

  var name = row.fileName;
  var url = row.filePath || row.files;
  // var suffix = url.substring(url.lastIndexOf("."), url.length);
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + url)
  a.click()
}


/** 修改按钮操作 */
function handleUpdateFile(row) {
  resetFile();
  const _attachmentId = row.attachmentId || ids.value
  getAttachment(_attachmentId).then(response => {
    fileForm.value = response.data;
    openFile.value = true;
  });
}
/** 修改付款信息按钮操作 */
function handleUpdateImplement(row) {
  resetImplement();
  const _Id = row.id || ids.value
  getImplement(_Id).then(response => {
    implementForm.value = response.data;
    openImplement.value = true;
  });
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

/** 提交按钮 */
function submitFileForm() {
  proxy.$refs["attachmentRef"].validate(valid => {
    if (valid) {

      // 定义 loading 实例变量
      let loadingInstance = null;
      if (fileForm.value.attachmentType == "5" || fileForm.value.attachmentType == "22") {
        //正数清单上传慢  加上loading
        loadingInstance = ElLoading.service({ fullscreen: true, text: '清单上传中...' });

      }

      if (fileForm.value.attachmentType == "6") {
        if (fileForm.value.completeDate == null || fileForm.value.completeDate == undefined) {
          console.log("fileForm.completeDate", fileForm.completeDate);

          proxy.$modal.msgError("上传竣工报告时必须填写竣工日期");
          return
        }
      }


      fileForm.value.fileName = getFileName(fileForm.value.filePath)
      fileForm.value.projectNo = projectNo.value
      if (fileForm.value.attachmentId != null) {
        updateAttachment(fileForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          if (loadingInstance) {
            loadingInstance.close();
          }
          openFile.value = false;
          getListParticipan(projectNo.value)
        }).finally(() => {
          loadingInstance.close();
        });
      } else {
        addAttachment(fileForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          if (loadingInstance) {
            loadingInstance.close();
          }
          openFile.value = false;
          getListParticipan(projectNo.value)
        }).finally(() => {
          loadingInstance.close();
        });
      }
    }
  });
}

function isImage(file) {
  return /\.(png|jpe?g|gif|bmp|webp)$/i.test(file);
}

/** 提交按钮 */
function submitimplementForm() {
  proxy.$refs["implementRef"].validate(valid => {
    if (valid) {
      implementForm.value.projectNo = projectNo.value
      if (implementForm.value.files) {
        implementForm.value.fileName = getFileName(implementForm.value.files)
      }
      if (implementForm.value.id != null) {
        updateImplement(implementForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openImplement.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addImplement(implementForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openImplement.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}



/** 删除按钮操作 */
function handleDeleteFile(row) {
  const _attachmentIds = row.attachmentId || ids.value;
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delAttachment(_attachmentIds);
  }).then(() => {
    getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}


/** 删除付款信息按钮操作 */
function handleDeleteImplement(row) {
  const _Id = row.id
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delImplement(_Id);
  }).then(() => {
    getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}



//添加参与人员
function addPerson() {
  //重置表单
  resetPer()
  // personList.value = []
  openOper.value = true
  title.value = "添加参与人员信息";
  //项目实施 字典值为2 写死
  personForm.value.phaseId = 3
}


//添加附件信息
function addFiles() {
  //重置表单
  resetFile()
  // personList.value = []
  openFile.value = true
  title.value = "添加附件信息";
  fileForm.value.phaseId = 3
}
//添加实施日志信息 销售负责人添加实施日志信息？
function addImplements() {
  //校验是否是销售负责人？
  // //立项前期阶段 需要添加项目经理id 2 销售 9 商务 7 财务 6
  // result = attachmentList.value.find(item => item.postId === 2);
  //重置表单
  resetImplement()
  implementForm.value.totalAmount = contractAmount.value//合同签订金额自动带出
  implementForm.value.fileType = 0 //默认选择第一个
  // personList.value = []
  openImplement.value = true
  //项目立项前期 字典值为1 写死
  implementForm.value.phaseId = 3
}


const { queryParams, form, rules, personForm, personRules, fileRules, ImplementRules, fileForm, implementForm, currentConfig } = toRefs(data);

const setHousekeeperName = (id) => {
  console.log("setHousekeeperName", id);
  if (id == undefined) {
    form.value.ousekeeperName = '';
    return
  }
  const filteredObjects = companyList.value.find((obj) => obj.id === id);
  form.value.ousekeeperName = '';
  console.log("filteredObjects", filteredObjects);
  form.value.housekeeperName = filteredObjects?.companyName || '';
}

function getCurrUser(id) {
  getPosts(id).then(response => {
    console.log("66666666", response);


  });
}


//判断是否是销售负责人 项目经理 销售 财务 商务

async function isSale() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 2,//项目实施 写死
    postIds: [2, 5]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  // haveImplement.value = await hasPermisson(params)
  haveAddPerson.value = await hasPermisson(params)
  console.log("添加信息", haveAddPerson.value);

}

//是否是财务
async function isFinance() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 2,//实施阶段 写死
    postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  finance.value = await hasPermisson(params)

  console.log("添加财务信息", finance.value);
}

async function hasPermisson(params) {
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}


// function getPhaseStatus(){
//   getStatus
// }

function initData() {
  getUser().then(response => {
    posts.value = response.posts;
    console.log("岗位信息", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

  getInfo().then((res) => {
    console.log("当前用户", res);
    getCurrUser(res.user.userId)
  })
    .catch((error) => {
      console.log("error", error);
    });
}

const setProjectTypeName = (datas) => {
  //对应的名称
  const filteredObjects = project_type.value.filter((obj) => datas.includes(obj.value));
  form.value.projectTypeName = '';
  const labels = filteredObjects.map((obj) => obj.label);
  form.value.projectTypeName = labels.length > 1 ? labels.join(',') : labels[0] || '';

};



/** 查询绩效基本信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAcceptTime && "" != daterangeAcceptTime) {
    // queryParams.value.params["beginAcceptTime"] = daterangeAcceptTime.value[0];
    // queryParams.value.params["endAcceptTime"] = daterangeAcceptTime.value[1];
    queryParams.value.beginAcceptTime = daterangeAcceptTime.value[0];
    queryParams.value.endAcceptTime = daterangeAcceptTime.value[1];
  }
  listProject(queryParams.value).then((response) => {
    console.log("response", response);
    projectList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
    console.log('projectList', projectList);

  });
}

// 取消按钮
function cancel() {
  console.log("关闭");
  open.value = false;
  openView.value = false
  reset();
  if (notificationInstance) {
    notificationInstance.close()
    notificationInstance = null // 清除实例引用
  }
  //判断是否是数据看板过来的 是则跳回去
  if (isDataView.value) {
    router.push({
      path: '/project/dataView',
    });
  }

}
// 取消按钮
function cancelPerson() {
  openOper.value = false;
  resetPer();
}

// 取消按钮
function cancelFile() {
  openFile.value = false;
  resetFile();
}


// 取消按钮
function canceImplement() {
  openImplement.value = false;
  resetImplement();
}


//获取用户详细信息
function getUserInfo() {
  getInfo().then((res) => {
    const user = res.user;
    form.value.createUserName = user.nickName;
    form.value.createUserId = user.userId;
    form.value.createDeptName = user.dept.deptName
    form.value.createDept = user.deptId
    console.log("user", form);
  })
    .catch((error) => {
      console.log("error", error);
    });


  // listDictionary().then(response => {
  //   form.value.phaseName = response.data?.rows[0]?.phaseName
  //   form.value.phaseCode = response.data?.rows[0]?.phaseCode
  // });

}
// 表单重置 
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null,
    companyName: null,
    companyType: null,
    companyNo: null
  };
  proxy.resetForm("projectRef");

}


const setCompanyTypeName = (datas) => {
  //对应的名称
  const filteredObjects = company_type.value.filter((obj) => datas.includes(obj.value));
  form.value.companyName = '';
  const labels = filteredObjects.map((obj) => obj.label);
  form.value.companyName = labels.length > 1 ? labels.join(',') : labels[0] || '';

};

// 表单重置
function resetPer() {
  personForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("participanRef");

}

// 表单重置
function resetFile() {
  fileForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("attachmentRef");

}

// 表单重置
function resetImplement() {
  implementForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("implementRef");

}



/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 同步数据 */
function handleSync() {
  syncData().then((response) => {
    proxy.$modal.msgSuccess("同步成功");
  });
}




/** 重置按钮操作 */
function resetQuery() {
  daterangeAcceptTime.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.minProjectAmount = null
  queryParams.value.maxProjectAmount = null
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.projectNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function setPostName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = posts.value.filter((obj) => obj.postId === id);
  // 清空 projectTypeName 字段
  personForm.value.postName = '';
  console.log("postName", filteredObjects);
  personForm.value.postName = filteredObjects[0].postName
}

function setPersonName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = userList.value.filter((obj) => obj.userId === id);
  // 清空 projectTypeName 字段
  personForm.value.participanName = '';
  console.log("filteredObjects[0]?.nickName", filteredObjects[0]?.nickName);

  personForm.value.participanName = filteredObjects[0]?.nickName
}


import amountView from "../amountView.vue";
const amountRef = ref()
const amountViewProjectNo = ref(0)
/** 添加立项前期信息 */
function handleUpdate(row) {
  amountViewProjectNo.value = row.projectNo
  activeName.value = "first"
  reset();
  isView.value = false
  const _projectNo = row.projectNo || ids.value;
  projectNo.value = row.projectNo //存放项目id
  openMessage()
  contractAmount.value = row.contractAmount
  getProject(_projectNo).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目基本信息";
  });
  isManger()
  getListParticipan(row.projectNo)

  getNextPer(row.projectNo);

  getPolicyPer()

}




const uploadPolicy = ref(false)

async function getPolicyPer() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  const res = await getPermission(params).then((response) => {
    console.log("是否是项目经理", response.data);
    uploadPolicy.value = response.data
    return response.data
  });
  return res

}



function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }
  listParticipan(params).then((response) => {
    console.log("response", response);
    personList.value = response.data
  });

  listAttachment(params).then((response) => {
    attachmentList.value = response.data;
  });


  listImplement(params).then((response) => {
    implementList.value = response.data;
  });

  listPay(params).then((response) => {
    payList.value = response.data;
  });



  isFinance()
  isSale()

  getCurrPhase(projectNo)

}


function handleUpdateParticipan(row) {
  // const _projectNo = row.projectNo || ids.value;
  // personForm.projectNo = row.projectNo
  // getProject(_projectNo).then((response) => {
  //   form.value = response.data;
  //   open.value = true;
  //   title.value = "修改基本信息";
  // });
  openOper.value = true
  personForm.value = row

}


function handleDeleteParticipan(row, index) {
  proxy.$modal
    .confirm('是否确认删除？')
    .then(async () => {
      if (row.id) {
        await delParticipan(row.id)
        proxy.$modal.msgSuccess("删除成功");
      }
      getListParticipan(form.value.projectNo)
    })
    .catch((error) => {
      // 捕获错误并提示用户
      console.error("删除操作失败", error);
      proxy.$modal.msgError("删除失败，请稍后再试");
    });
}



/** 阶段管理操作 */
async function handleView(row) {
  activeName.value = "first"
  reset();
  const _projectNo = row.projectNo || ids.value;
  getListParticipan(row.projectNo)
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    openView.value = true;
    isView.value = true
  });

}


async function nextPhase() {
  //新版点击下一步 1.下一步按钮只开给需要审核的人 隐藏与显示 获取当前配置的环节规则 请求接口校验
  if (form.value.acceptTime == null || form.value.acceptTime == '') {
    proxy.$modal.msgError("请填写预计验收日期");
    return
  }

  if (form.value.acceptTime < form.value.planDate) {
    proxy.$modal.msgError("预计验收日期不能早于预计开始日期");
    return
  }




  if (form.value.policy == undefined || form.value.policy == null || form.value.policy == '') {
    proxy.$modal.msgError("请选择是否有项目保险单");
    return
  }

  if (form.value.policy == '2') {
    if (form.value.policyFile == undefined || form.value.policyFile == null || form.value.policyFile == '') {
      proxy.$modal.msgError("项目经理未上传项目保险单附件");
      return
    }
  }


  submitForm()

  let params = {
    projectNo: projectNo.value,
    id: 3//项目实施
  }
  //校验该环节的所有配置
  const result = await getCheck(params).then(response => {//立项阶段 id写死
    console.log("项目实施校验", response);
    return response
  });
  if (result.data.permission == false) {
    proxy.$modal.msgError(result.data.message);
    return
  }
  //校验通过 更新当前阶段信息



  let updateParams = {
    id: currenrPhaseId.value,
  }
  const updateResult = await updatePhase(updateParams).then((response) => {
    console.log("更新阶段", response);
    return response
  });

  if (updateResult.data.status == 2) {//如果该环节已完成 插入下一个环节
    let addParams = {
      projectNo: projectNo.value,
      phaseId: 4,//项目验收
      remark: form.value.phaseRemark//留言
    }
    addPhase(addParams).then((response) => {

    })
  }

  proxy.$modal.msgSuccess("提交成功");
  status.value = 2
  open.value = false



  let currPhase = {
    projectNo: projectNo.value,
    phaseId: 3
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data?.status && response.data?.status == '2') {//如果该环节已完成 跳转到下一个环节

      router.push({
        path: '/accept/projectAccept',
        query: { projectNo: projectNo.value }
      });

    }

    else {
      getList()
    }

  });

}


function getCurrPhase(projectNo) {//查询当前阶段有无完成
  let currPhase = {
    projectNo: projectNo,
    phaseId: 3//实施阶段 0
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data == null) {
      //  currenrPhaseId.value = response.data.id
    } else {
      status.value = response.data.status
      currenrPhaseId.value = response.data.id
    }
  });
}


function selectCompany(query) {
  console.log("queryquery", query);
  loadingQuery.value = true
  let params = {
    companyName: query
  }
  listCompany(params).then((response) => {
    companyList.value = response.data
    loadingQuery.value = false
  });
}


/** 提交按钮 */
function submitForm() {

  proxy.$refs["projectRef"].validate((valid) => {
    if (valid) {
      if (form.value.projectNo != null) {
        updateProject(form.value).then((response) => {
        });
      }
    }
  });
}

//是否是项目经理或销售负责人
async function isManger() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 5]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  manger.value = await hasPermisson(params)
  console.log("是否是项目经理或销售负责人ger.value", manger.value);
  formDisabled.value = !manger.value
}




/** 提交按钮 */
function submitPersonFormback() {

  console.log("personForm", personForm.value);

  proxy.$refs["participanRef"].validate((valid, errors) => {
    if (!valid) {
      proxy.$modal.msgError("请先完善参与人员信息，至少添加一名销售负责人");
      return;
    }
    // 验证通过，处理数据
    try {
      if (personForm.value.id != null && personForm.value.id != undefined) {
        // 查找是否有匹配的 id
        const index = personList.value.findIndex(item => item.id === personForm.value.id);
        if (index !== -1) {
          // 如果找到匹配的 id，替换对应下标的数据
          personList.value[index] = { ...personForm.value }; // 使用扩展运算符创建新对象以避免引用问题
        } else {
          // 如果没有找到匹配的 id，直接添加到列表中
          personList.value.push({ ...personForm.value });
        }
      } else {
        // 如果 id 不存在，直接添加到列表中
        personList.value.push({ ...personForm.value });
      }

      // 关闭操作窗口
      openOper.value = false;

      // 提示成功
      proxy.$modal.msgSuccess("操作成功");
    } catch (error) {
      // 捕获错误并提示用户
      console.error("操作失败", error);
      proxy.$modal.msgError("操作失败，请稍后再试");
    }
  });
}



/** 提交按钮 */
function submitPersonForm() {
  proxy.$refs["participanRef"].validate(valid => {
    if (valid) {
      personForm.value.projectNo = projectNo.value
      if (personForm.value.id != null) {
        updateParticipan(personForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openOper.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addParticipan(personForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openOper.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}



function submitPhaseForm() {
  console.log("");

}

/** 删除按钮操作 */
function handleDelete(row) {
  const _projectNos = row.projectNo || ids.value;
  proxy.$modal
    .confirm('是否确认删除绩效基本信息编号为"' + _projectNos + '"的数据项？')
    .then(function () {
      return delProject(_projectNos);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/project/export",
    {
      ...queryParams.value,
    },
    `project_${new Date().getTime()}.xlsx`
  );
}

function getCompanys() {
  getCompanyList(queryParams.value).then((response) => {
    companyList.value = response.data.map(item => ({
      ...item, // 保留原始属性
      value: item.id, // 添加 value 字段
      label: item.companyName, // 添加 label 字段
    }));
  });
  getFinanceList(queryParams.value).then((response) => {
    financeList.value = response.data.map(item => ({
      ...item, // 保留原始属性
      value: item.finance, // 添加 value 字段
      label: item.finance, // 添加 label 字段
    }));
  });

}

function getCurrentDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day}`;
};




function getCurrPhaseConfig() {
  getDictionary(3).then(response => {//项目实施
    currentConfig.value = response.data;
  });
}

function getNextPer(projectNo) {
  let params = {
    projectNo: projectNo,
    id: 3//项目实施
  }
  getNextPermission(params).then(response => {//立项阶段 id写死
    console.log("实施 下一步权限", response);
    haveNext.value = response.data.permission

    addPersonPer.value = response.data.addPerson
    addFilePer.value = response.data.addFile
    addPayPer.value = response.data.addPay
    addImplementPer.value = response.data.addImplement
    addWarrantyPer.value = response.data.addWarranty
    addAccounting.value = response.data.addAccounting

  });
}

getCurrPhaseConfig()

getList();
getCompanys();
initData()

const isDataView = ref(false)
onMounted(() => {
  loadUserColumnConfig()
  nextTick(() => {
    console.log("实施跳转", route.query);
    if (route.query?.projectNo) {
      //判断是不是从数据看板跳过来的 如果是 关闭页面的时候跳回去
      if (route.query?.type != undefined && route.query?.type != null && route.query?.type == 'dataView') {
        isDataView.value = true
      }

      getProject(route.query?.projectNo).then((response) => {
        form.value = response.data;
        handleUpdate(form.value)

        // 创建一个新的 query 对象，排除 projectNo
        const { projectNo, ...restQuery } = route.query;
        // 使用 replace 更新路由，不保留 projectNo
        router.replace({
          path: route.path,
          // query: restQuery
        });
      });
    }
  })

});


// 组件卸载前自动关闭通知
onBeforeUnmount(() => {
  closeNotification()
})


// 关闭通知的方法
function closeNotification() {
  if (notificationInstance) {
    notificationInstance.close()
    notificationInstance = null
  }
}

// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "项目阶段", prop: "phaseName", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "预计验收日期", prop: "acceptTime", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "项目类型", prop: "projectTypeName", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },
]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])

// 当前可见列列表（根据 selectedProps 排序后的结果）
const visibleColumns = computed(() => {
  return selectedProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter(Boolean)
})



// 当前可见列（根据用户选择动态变化）
const selectedColumns = ref([...allColumns])


const saveColumnConfig = async () => {

  console.log('保存配置', selectedProps.value);


  // 调用保存到后端的接口
  await saveUserTableConfig({ configs: selectedProps.value, type: "impl" })
  proxy.$modal.msgSuccess("保存配置成功");

}

const getWidth = (prop) => {
  switch (prop) {
    case 'projectName':
    case 'approvalDate':
    case 'updateTime':
    case 'acceptTime':
      return 200;
    case 'housekeeperName':
      return 300;
    default:
      return undefined;
  }
}

async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "impl" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}


import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

</script>
